package com.ztom.top100;

/**
 * 删除链表的倒数第 n 的节点
 * <p>
 * https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/
 *
 * @author ZhangTao
 */
public class Code10RemoveNthFromEnd {

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public ListNode removeNthFromEnd(ListNode head, int n) {
        // 哨兵
        ListNode dummy = new ListNode(-1, head);
        if (head == null) {
            return dummy.next;
        }

        // 先后指针: 间隔为 n 个节点
        ListNode first = head;
        ListNode second = dummy;

        for (int i = 0; i < n; i++) {
            if (first == null) {
                return dummy.next;
            }
            first = first.next;
        }
        while (first != null) {
            first = first.next;
            second = second.next;
        }

        // second 就是倒数第 n 个节点的 pre 节点
        ListNode nodeN = second.next;
        second.next = nodeN.next;
        nodeN.next = null;
        nodeN = null;

        return dummy.next;
    }
}
